package dfrz.com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author PuXiaLing
 * @description: TODO
 * @date 2024/1/8 11:28
 */

public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //uri等信息只在httpServletRequest存在，需要强制转换类型
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        String uri=httpServletRequest.getRequestURI();
        System.out.println("拦截");
        //登录界面/登录请求，退出请求，注册注册请求不需要拦截
        if (uri.equals("/")||uri.equals("/shop/logout")||uri.equals("/shop/login")||uri.equals("/login.jsp")||uri.equals("/api/upload")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //非法请求，回到登录界面
            if (httpServletRequest.getSession().getAttribute("shop")==null){
                httpServletResponse.sendRedirect("/login.jsp");
            }else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
